"""
RedFire 环境配置管理工具
简化版配置加载器和环境管理
"""

import os
import yaml
from typing import Dict, Any, Optional
from dataclasses import dataclass
from pathlib import Path


@dataclass
class DatabaseConfig:
    """数据库配置"""
    host: str
    port: int
    database: str
    username: str
    password: str
    pool_size: int = 10
    max_overflow: int = 20


@dataclass
class ServiceConfig:
    """服务配置"""
    host: str
    port: int
    workers: int = 1


class EnvironmentManager:
    """环境管理器"""
    
    def __init__(self, environment: str = None):
        self.environment = environment or os.getenv('REDFIRE_ENV', 'development')
        self._config_cache = {}
    
    @staticmethod
    def get_required_env_vars() -> Dict[str, str]:
        """获取必需的环境变量列表"""
        return {
            # 数据库密码
            'MYSQL_ROOT_PASSWORD': 'MySQL Root密码',
            'MYSQL_APP_PASSWORD': 'MySQL应用密码',
            'POSTGRES_PASSWORD': 'PostgreSQL密码',
            'REDIS_PASSWORD': 'Redis密码',
            
            # API密钥
            'TUSHARE_API_KEY': 'Tushare API密钥',
            'JWT_SECRET': 'JWT密钥',
            
            # 监控配置
            'GRAFANA_PASSWORD': 'Grafana管理员密码',
        }
    
    @staticmethod
    def check_environment() -> Dict[str, bool]:
        """检查环境变量设置情况"""
        required_vars = EnvironmentManager.get_required_env_vars()
        status = {}
        
        for var_name, description in required_vars.items():
            status[var_name] = os.getenv(var_name) is not None
        
        return status
    
    @staticmethod
    def generate_env_template() -> str:
        """生成环境变量模板"""
        required_vars = EnvironmentManager.get_required_env_vars()
        template_lines = [
            "# RedFire 数据库系统环境变量配置",
            "# 复制此文件为.env并填入实际值",
            ""
        ]
        
        for var_name, description in required_vars.items():
            template_lines.append(f"# {description}")
            template_lines.append(f"{var_name}=")
            template_lines.append("")
        
        return "\n".join(template_lines)
    
    def get_database_url(self, db_type: str = "mysql") -> str:
        """获取数据库连接URL"""
        if db_type == "mysql":
            host = os.getenv('MYSQL_HOST', 'localhost')
            port = os.getenv('MYSQL_PORT', '3306')
            database = os.getenv('MYSQL_DATABASE', 'redfire_trading')
            username = os.getenv('MYSQL_USER', 'redfire_app')
            password = os.getenv('MYSQL_APP_PASSWORD', '')
            
            return f"mysql+pymysql://{username}:{password}@{host}:{port}/{database}"
        
        elif db_type == "postgresql":
            host = os.getenv('POSTGRES_HOST', 'localhost')
            port = os.getenv('POSTGRES_PORT', '5432')
            database = os.getenv('POSTGRES_DATABASE', 'redfire_analytics')
            username = os.getenv('POSTGRES_USER', 'redfire_app')
            password = os.getenv('POSTGRES_PASSWORD', '')
            
            return f"postgresql://{username}:{password}@{host}:{port}/{database}"
        
        else:
            raise ValueError(f"不支持的数据库类型: {db_type}")
    
    def get_redis_config(self) -> Dict[str, Any]:
        """获取Redis配置"""
        return {
            'host': os.getenv('REDIS_HOST', 'localhost'),
            'port': int(os.getenv('REDIS_PORT', '6379')),
            'password': os.getenv('REDIS_PASSWORD'),
            'db': int(os.getenv('REDIS_DB', '0')),
            'decode_responses': True
        }
    
    def validate_environment(self) -> Dict[str, Any]:
        """验证环境配置"""
        results = {
            'is_valid': True,
            'missing_vars': [],
            'warnings': []
        }
        
        # 检查必需的环境变量
        env_status = self.check_environment()
        missing_vars = [var for var, exists in env_status.items() if not exists]
        
        if missing_vars:
            results['is_valid'] = False
            results['missing_vars'] = missing_vars
        
        # 检查数据库连接
        try:
            mysql_url = self.get_database_url('mysql')
            if not mysql_url or 'None' in mysql_url:
                results['warnings'].append('MySQL连接配置不完整')
        except Exception as e:
            results['warnings'].append(f'MySQL配置错误: {e}')
        
        try:
            postgres_url = self.get_database_url('postgresql')
            if not postgres_url or 'None' in postgres_url:
                results['warnings'].append('PostgreSQL连接配置不完整')
        except Exception as e:
            results['warnings'].append(f'PostgreSQL配置错误: {e}')
        
        return results


# 使用示例和CLI工具
def main():
    """命令行工具入口"""
    import argparse
    
    parser = argparse.ArgumentParser(description='RedFire 环境管理工具')
    parser.add_argument('--check', action='store_true', help='检查环境变量')
    parser.add_argument('--template', action='store_true', help='生成环境变量模板')
    parser.add_argument('--validate', action='store_true', help='验证环境配置')
    
    args = parser.parse_args()
    
    manager = EnvironmentManager()
    
    if args.template:
        print(manager.generate_env_template())
    elif args.check:
        env_status = manager.check_environment()
        missing_vars = [var for var, exists in env_status.items() if not exists]
        
        if missing_vars:
            print(f"缺少环境变量: {', '.join(missing_vars)}")
            print("\n使用 --template 参数生成环境变量模板")
        else:
            print("所有必需的环境变量都已设置")
    elif args.validate:
        results = manager.validate_environment()
        
        if results['is_valid']:
            print("✅ 环境配置验证通过")
        else:
            print("❌ 环境配置验证失败")
            if results['missing_vars']:
                print(f"缺少环境变量: {', '.join(results['missing_vars'])}")
        
        if results['warnings']:
            print("⚠️ 警告:")
            for warning in results['warnings']:
                print(f"  - {warning}")
    else:
        parser.print_help()


if __name__ == "__main__":
    main()
